<script>
import ImageWithUpload from './index'
import axios from 'axios'
export default {
    components:{
        ImageWithUpload
    },
    props:{
        headers: {
            type: Object,
            default() {
                return {}
            }
        },
        data: {
            type: Object,
            default() {
                return {}
            }
        },
    },
    data(){
        return {
            folder:'',
            url: `${process.env.VUE_APP_UPLOAD}api/v1/upload/file`
        }
    },
    computed:{
        attrs(){
            const attrs = this.$attrs

            attrs.handleUpload = this.handleFileSelected
            return attrs
        },
        listeners(){
            const listeners = this.$listeners
            return listeners
        }
    },
    methods:{
        upload(file, onChange) {
            const data = new FormData()

            for(let key in this.data){
                data.append(key,this.data[key])
            }

            data.append('file', file)
            data.append('folder', this.folder)
            

            return axios
                .post(
                    this.url, 
                    data, 
                    {
                        headers: { ...this.headers },
                        onUploadProgress(e) {
                            const { loaded, total } = e
                            const progress = parseFloat((loaded / total * 100).toFixed(2))
                            onChange?.(progress)
                        }
                    }
                )
                .then(result => result.data)
        },
        handleFileSelected(task){
            const {
                file,
                handlers:{
                    onStart,
                    onChange,
                    onSuccess,
                    onFailed
                }
            } = task
            onStart?.()
            this.upload(file,onChange)
            .then(data => {
                if(data.code != 200){
                    throw new Error(data.message??'上传失败')
                }
                onSuccess?.(data.data.path)
                this.$emit('success',data)
            })
            .catch((e) => {
                onFailed?.()
                this.$emit('fail',e)
            })
        }
        
    }
}
</script>

<template>
    <ImageWithUpload 
        v-bind="attrs"
        v-on="listeners"
    />
</template>